﻿using System;
using System.Configuration;
using System.IO.Compression;
using System.Web.Mvc;

namespace WorkWriter.Controllers
{
    public class BaseController : Controller
    {
        protected static NoteManger.NoteRemote noteContext = null;

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            string controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string action = filterContext.ActionDescriptor.ActionName;
            string neglectActions = ",Error,About,";
            if (SysContext.User == null && controller != "Account" && action != "Login" && neglectActions.IndexOf("," + action + ",") < 0)
            {
                if (controller == "Home" && action == "Index") filterContext.Result = RedirectToAction("Login", "Account");
                else filterContext.Result = new HttpUnauthorizedResult();
            }
            base.OnAuthorization(filterContext);
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            this.InitContext(filterContext);
            base.OnActionExecuting(filterContext);
        }
        protected override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            string acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
            if (String.IsNullOrEmpty(acceptEncoding)) return;
            var response = filterContext.HttpContext.Response;
            acceptEncoding = acceptEncoding.ToUpperInvariant();

            if (acceptEncoding.Contains("GZIP"))
            {
                response.AppendHeader("Content-Encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("DEFLATE"))
            {
                response.AppendHeader("Content-Encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }

        protected override void HandleUnknownAction(string actionName)
        {
            if (this.Request.IsAjaxRequest()) throw new Exception("请求的服务不存在，请检查Url地址是否正确.");
            else this.Redirect("~/404.htm");
        }
        protected override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            //if (ex is LogicException) logger.Write(Level.Error, ex);
            //else logger.Write(Level.Fatal, ex);
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.ExceptionHandled = true;
                filterContext.Result = Json(false, filterContext.Exception.Message);
                //if (ex is LogicException) filterContext.Result = Json(false, filterContext.Exception.Message);
                //else filterContext.Result = Json(false, "系统错误，请联系管理员！");

            }
            else
            {
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Session["_EXCEPTION_"] = ex;
                filterContext.Result = RedirectToAction("Error");
            }
        }

        public ActionResult Error()
        {
            return View();
        }
        private void InitContext(ActionExecutingContext filterContext)
        {
            if (noteContext == null)
            {
                noteContext = filterContext.HttpContext.Cache["NOTE_MANAGER"] as NoteManger.NoteRemote;
                if (noteContext == null)
                {
                    string remoteUrl = ConfigurationManager.AppSettings["NoteRemoteUrl"];
                    if (remoteUrl == null) throw new Exception("无法连接服务器，请确保配置正确。");
                    noteContext = (NoteManger.NoteRemote)Activator.GetObject(typeof(NoteManger.NoteRemote), remoteUrl);
                    if (noteContext == null) throw new Exception("无法连接服务器，请确保配置正确。");
                    noteContext.ConnectionTest();
                    filterContext.HttpContext.Cache["NOTE_MANAGER"] = noteContext;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="success">返回请求执行情况,true:成功，无异常</param>
        /// <returns></returns>
        protected JsonResult Json(bool success)
        {
            return Json(new RequestResult { success = success });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="success">返回请求执行情况,false:失败，message:异常信息，或失败原因</param>
        /// <param name="message"></param>
        /// <returns></returns>
        protected JsonResult Json(bool success, string message)
        {
            return Json(new RequestResult { success = success, message = message });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="success">返回请求执行情况,false:失败，message:异常信息，或失败原因</param>
        /// <param name="message"></param>
        /// <returns></returns>
        protected JsonResult Json(bool success, object data)
        {
            return Json(new RequestResult { success = success, data = data });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="success">返回请求执行情况,true:成功， false:失败，message:异常信息，或失败原因, data：需要反馈的数据</param>
        /// <param name="message"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        protected JsonResult Json(bool success, string message, object data)
        {
            return Json(new RequestResult { success = success, message = message, data = data });
        }

        protected JsonResult Json(RequestResult result)
        {
            object o = result;
            return Json(o);
        }

    }
}